import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class UDPEchoSever {
     static DatagramSocket  socket;
    public UDPEchoSever(int pase) throws SocketException {
        socket=new DatagramSocket(pase);
    }
    public void start() throws IOException {
        System.out.println("服务器已启动");
        while (true){
            //接收用户发来的数据
            DatagramPacket packet=new DatagramPacket(new byte[1024],1024);
            socket.receive(packet);
            //接收数据
            String request=new String(packet.getData(),0,packet.getLength(),"UTF-8");
            //通过计算响应
            String response=process(request);
            DatagramPacket responsepacket=new DatagramPacket(request.getBytes(StandardCharsets.UTF_8),0,request.length(), packet.getSocketAddress());
            //发送响应
            socket.send(responsepacket);
            System.out.printf("[%s:%d] request :%s,response=%s\n",packet.getAddress().toString(),packet.getPort(),request);
        }
    }

    public String process(String request){
        return request;
    }
    public static void main(String[] args) throws IOException {
        UDPEchoSever sockpt=new UDPEchoSever(8888);
        sockpt.start();
    }
}
